import path from 'path';
import Koa from 'koa';
import koaStatic from 'koa-static';
import session from 'koa-session';
import cors from 'koa2-cors';
import proxy from 'koa-proxies';

import { PROXY_LIST } from '../config';
import router from './routes';

const isDev = process.env.NODE_ENV !== 'production';

const app = new Koa();
app.keys = ['react-template'];
app.proxy = true;

// 静态目录
app.use(koaStatic(path.join(__dirname, '../static')));
if (!isDev) app.use(koaStatic(path.join(__dirname, '../dist')));

// session
const SESSION_CONFIG = {
  key: 'react.template',
  maxAge: 1000 * 60 * 10,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: true,
};
app.use(session(SESSION_CONFIG, app));

// ejs
const render = require('koa-ejs');
render(app, {
  root: isDev ? path.resolve(__dirname, '../_webpack') : path.resolve(__dirname, '..', 'dist'),
  layout: false,
  viewExt: 'html',
  cache: true,
  debug: isDev,
});

// 设置跨域
app.use(cors({
  origin: '*',
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE', 'PUT'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

// 路由
app.use(router.routes(), router.allowedMethods());

// http代理
for (let key in PROXY_LIST) {
  app.use(proxy(key, PROXY_LIST[key]));
}

if (isDev) { // 开发环境
  const history = require('koa2-connect-history-api-fallback');
  app.use(history({ whiteList: ['/api'] }));

  // webpack
  const webpack = require('webpack');
  const { devMiddleware, hotMiddleware } = require('koa-webpack-middleware');

  const webpackConfig = require('../_webpack/webpack.config.koa');
  const compile = webpack(webpackConfig);

  app.use(devMiddleware(compile, {
    noInfo: false,
    quiet: false,
    publicPath: webpackConfig.output.publicPath,
    stats: 'minimal',
  }));
  app.use(hotMiddleware(compile, {
    // log: console.log,
    // path: '/__webpack_hmr',
    // heartbeat: 10 * 1000
  }));
} else { // 生产环境
  app.use(async (ctx) => {
    await ctx.render('app');
  });
}

export default app;